package homework.gademo.service;

import homework.gademo.common.GoogleAuthenticator;
import homework.gademo.common.SessionUtil;
import homework.gademo.dao.UserInfoRepository;
import homework.gademo.domain.UserInfo;

import javax.annotation.Resource;






import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImp implements UserService {

	@Resource
	UserInfoRepository userInfoRepository;
	
	public boolean register(UserInfo userInfo) {
		if (userInfoRepository.save(userInfo) != null) {
			return true;
		}
		return false;
		
	}

	public boolean login(UserInfo userInfo,Long gaCode) {
		UserInfo tmp;
		if (userInfo.getUserName() != null) {
			tmp = userInfoRepository.findByUserName(userInfo.getUserName());
			if (tmp != null) {
				GoogleAuthenticator ga = new GoogleAuthenticator();
				boolean isGaPass = ga.check_code(tmp.getGoogleAuthKey(), gaCode, System.currentTimeMillis());
				if (tmp.getPassword().equals(userInfo.getPassword())&&isGaPass) {
					SessionUtil.setSessionAttribute(SessionUtil.SESSION_KEY_USER_ID, userInfo.getUserName());
					return true;
				}
			}

		}
		return false;
	}

	public boolean logout() {
		// TODO Auto-generated method stub
		return false;
	}

	public UserInfo getCurrentUser() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getGoogleKey() {
		return GoogleAuthenticator.generateSecretKey();
	}

}
